// pages/wallet/addbankcard/index.js
const app = getApp() // 引入app
import _request from '../../../utils/request.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imgUrl: app.globalData.imgUrl, //全局img路径
    showtypeList: [],
    showtype: false,
    tsctype: '请选择开户银行',
    bank: null,
    mobile: '',
    name: '',
    cardNo: '',
    userNo: '',
    code: '',
    oldtsctype: '',
    oldbank: '',
    oldopenBank: '',
    btnvisible: true,
    count_down: 60,
    userObj: null,
    openBank: '',
    birthDay: '',
    showidType: false,
    showgender: false,
    gendername: '',
    oldgendername: null,
    goUrl: '',
    genderlist: [{
      name: '男',
      type: 'M'
    }, {
      name: '女',
      type: 'F'
    }],
    checkUserStatus: '',
    defaultindex: 0,
    oriTransId: '',
    gender: '', // MF-男女
    idType: 'A' // A大陆身份证 E-港澳居民往来大陆通行证 F-台湾居民往来大陆通行证
  },

  // 性别显示
  showgender() {
    this.setData({
      showgender: true
    })
    // 第一次默认选中
    if (this.data.gendername == '') {
      this.setData({
        oldgendername: this.data.genderlist[0],
      })
    }
  },

  // 银行卡关闭
  onCancelgender() {
    this.setData({
      showgender: false
    })
  },


  //  性别确定
  onConfirmgender() {
    this.setData({
      showgender: false,
      gendername: this.data.oldgendername,
    })
  },

  // 获取性别选择类型
  onChangegender(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    this.setData({
      oldgendername: value,
    })
  },

  // 银行卡显示
  showType() {
    this.setData({
      showtype: true
    })
    // 第一次默认选中
    if (this.data.tsctype == '请选择开户银行') {
      this.setData({
        defaultindex: 0,
        oldtsctype: this.data.showtypeList[0].bankname,
        oldbank: this.data.showtypeList[0],
        oldopenBank: this.data.showtypeList[0].bankcode
      })
    }
  },

  // 银行卡关闭
  onCancel() {
    this.setData({
      showtype: false,

    })
  },

  // 银行卡确定
  onConfirm() {
    this.setData({
      showtype: false,
      tsctype: this.data.oldtsctype,
      bank: this.data.oldbank,
      openBank: this.data.oldopenBank
    })
  },

  // 获取验证码
  onCode() {
    const {
      bank,
      name,
      cardNo,
      code,
      tsctype,
      mobile,
      openBank,
      idType,
      gendername,
      birthDay,
      userNo,
      oriTransId,
      checkUserStatus
    } = this.data
    _request.postObj('/tfs/bindCardRequest', {
      userId: wx.getStorageSync('userid'),
      openBank: openBank,
      cardNo: cardNo,
      mobileNo: mobile,
    }).then((res) => {
      if (res.data.code === 200) {
        this.setData({
          oriTransId: res.data.data.transId
        })

        this.get_code_settime()
      }
    }).catch((error) => {
      console.log(error, 'error');
    })
  },

  // 获取银行卡选择类型
  onChangeType(event) {
    const {
      picker,
      value,
      index
    } = event.detail;
    this.setData({
      defaultindex: index,
      oldtsctype: value.bankname,
      oldbank: value,
      oldopenBank: value.bankcode
    })
  },

  // 持卡人姓名
  getinput(e) {
    let value = e.detail.value
    this.setData({
      name: value
    })
  },

  // 出生年月日
  getbirthDay(e) {
    let value = e.detail.value
    this.setData({
      birthDay: value
    })
  },

  // 银行卡号
  getCardnum(e) {
    let value = this.validateNumber(e.detail.value)
    this.setData({
      cardNo: value
    })
  },

  // 身份证卡号
  getUserno(e) {
    let value = this.validateNumber(e.detail.value)
    this.setData({
      userNo: value
    })
  },

  // 银行预留手机
  getPhonenum(e) {
    let value = this.validateNumber(e.detail.value)
    this.setData({
      mobile: value
    })
  },

  // 手机验证码
  getCode(e) {
    let value = this.validateNumber(e.detail.value)
    this.setData({
      code: value
    })
  },

  // 过滤
  validateNumber(val) {
    return val.replace(/\D/g, '')
  },

  // 绑定提现账户
  onBind() {
    const {
      bank,
      name,
      cardNo,
      code,
      tsctype,
      mobile,
      openBank,
      idType,
      gendername,
      birthDay,
      userNo,
      oriTransId,
      checkUserStatus
    } = this.data
    let vm = this
    console.log(this.data);
    // 绑定验证 (data=1未实名，5是已实名)
    if (checkUserStatus == 5) {
      vm.getRule1() && _request.postObj('/tfs/tfsRegister', {
        userId: wx.getStorageSync('userid'),
        openBank: openBank,
        cardNo: cardNo,
        idNo: userNo,
        mobileNo: mobile,
        custName: name,
        idType,
        gender: gendername.type,
        birthDay
      }).then((res) => {
        if (res.data.code == 200) {
          let retUrl = res.data.data.retUrl.split('?')
          let token = retUrl[1].split('=')[1]
          wx.showToast({
            title: '前往验证',
            icon: 'none',
            duration: 2000
          })
          this.setData({
            openBank: '',
            cardNo: '',
            userNo: '',
            mobile: '',
            name: '',
            gendername: '',
            birthDay: '',
            tsctype: '请选择开户银行',
            bankcode: '',
            bank: null
          })
          wx.navigateTo({
            // 跳转到webview页面
            url: '/component/verifybankcard/index?url=' + retUrl[0] + '&token=' + token,
          });
        }
      })
    } else {
      vm.getRule() && _request.postObj('/tfs/bindCardVeri', {
        userId: wx.getStorageSync('userid'),
        openBank: openBank,
        cardNo: cardNo,
        mobileNo: mobile,
        oriTransId,
        phoneDynCode: code
      }).then((res) => {
        if (res.data.code == 200) {
          wx.showToast({
            title: '绑定成功',
            icon: 'none',
            duration: 2000,
          })
          this.setData({
            openBank: '',
            cardNo: '',
            userNo: '',
            mobile: '',
            name: '',
            gendername: '',
            birthDay: '',
            tsctype: '请选择开户银行',
            bankcode: '',
            bank: null
          })
          setTimeout(() => {
            wx.navigateBack({ //返回上一个页面
              delta: 1,
            })
          }, 1000);
        } else if (res.data.code == 403) {
          wx.showToast({
            title: '输入的银行卡号有误，请重新输入',
            icon: 'none',
            duration: 2000,
            success: (() => {

            })
          })
        }
      }).catch((error) => {
        console.log(error, 'error');
      })
    }
  },

  // 验证规则
  getRule1() {
    const {
      name,
      bank,
      cardNo,
      mobile,
      idType,
      gendername,
      birthDay,
      userNo
    } = this.data
    if (!name) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return false
    } else if (!userNo) {
      wx.showToast({
        title: '请输入身份证',
        icon: 'none'
      })
      return false
    } else if (!gendername) {
      wx.showToast({
        title: '请选择性别',
        icon: 'none'
      })
      return false
    } else if (!birthDay) {
      wx.showToast({
        title: '请输入出生年月日',
        icon: 'none'
      })
      return false
    } else if (!bank) {
      wx.showToast({
        title: '请选择开户银行',
        icon: 'none'
      })
      return false
    } else if (!cardNo) {
      wx.showToast({
        title: '请输入卡号',
        icon: 'none'
      })
      return false
    } else if (!mobile) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return false
    } else {
      return true
    }
  },

  getRule() {
    const {
      bank,
      name,
      cardNo,
      code,
      mobile
    } = this.data
    if (!name) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      })
      return false
    } else if (!bank) {
      wx.showToast({
        title: '请选择开户银行',
        icon: 'none'
      })
      return false
    } else if (!cardNo) {
      wx.showToast({
        title: '请输入卡号',
        icon: 'none'
      })
      return false
    } else if (!mobile) {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none'
      })
      return false
    }
    // else if(!code){
    //   wx.showToast({
    //     title: '请输入验证码',
    //     icon: 'none'
    //   })
    //   return false
    // }
    else {
      return true
    }
  },

  //验证码按钮倒计时方法
  get_code_settime(that) {
    var that = this;
    let countDown = that.data.count_down; //获取倒计时初始值
    that.setData({
      //这里把setInterval复制给变量名timer
      timer: setInterval(function () {
        // 每隔一秒减1
        countDown--;
        that.setData({
          btnvisible: false, //此处用于隐藏验证码点击按钮，使倒计时显示
          count_down: countDown //倒计时计数 
        })
        //当计数为0时，清空定时器，使验证码按钮再次显示
        if (countDown == 0) {
          clearInterval(that.data.timer); //清除timer，
          that.setData({
            btnvisible: true,
            count_down: '60'
          })
        }
      }, 1000)
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 获取用户已绑定的银行卡列表
    _request.get('/settings/getAllBank', {}).then((res) => {
      this.setData({
        showtypeList: res.data.data
      })
    }).catch((error) => {
      console.log(error, 'error');
    })

    // 实名状态
    // _request.get('/userAuthApply/getApplyStatus', {
    //   userId: wx.getStorageSync('userid')
    // }).then((res) => {
    //   this.setData({
    //     userObj: res.data.data
    //   })
    // }).catch((error) => {
    //   console.log(error, 'error');
    // })

    // 是否在厦门银行实名过 (data=5未实名，1是已实名)
    _request.postObj('/tfs/checkUserStatus', {
      userId: wx.getStorageSync('userid'),
    }).then((res) => {
      this.setData({
        checkUserStatus: res.data.data
      })
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})